/*
 * Copyright (c) 2024 iSOFT INFRASTRUCTURE SOFTWARE CO., LTD.
 * easyAda is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *          http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */

#ifndef KS_STRING_H
#define KS_STRING_H

#include <stdlib/assert.h>
#include <stdlib/ks_stddef.h>

static inline void ks_memset(void *p, int value, size_t size)
{
    int *pp = p;

    assert(((unsigned long)p & 0x3) == 0);
    assert((size & 0x3) == 0);

    size >>= 2;

    while (size != 0UL) {
        *pp = value;
        pp++;
        size--;
    }
}

void *ks_memcpy(void *t, const void *s, size_t size);

static inline size_t ks_strlen(const char *str)
{
    size_t result = 0;

    if (str != NULL) {
        while (*str != '\0') {
            result++;
            str++;
        }
    }

    return result;
}

static inline size_t ks_strcpy(char *dst, const char *src)
{
    size_t      result = 0;
    char       *p      = dst;
    const char *q      = src;

    if ((dst != NULL) && (src != NULL)) {
        while (*q != '\0') {
            *p = *q;
            p++;
            q++;
            result++;
        }
    }
    return result;
}

static inline char *ks_strcat(char *dest, const char *src)
{
    char *ret = dest;
    dest += ks_strlen(dest);
    while (*src != '\0') {
        *dest = *src;
        dest++;
        src++;
    }
    *dest = '\0';
    return ret;
}

static inline int ks_strcmp(const char *str1, const char *str2)
{
    const char *ks__str1 = str1;
    const char *ks__str2 = str2;
    while ((*ks__str1 != '\0') && (*ks__str2 != '\0')) {
        if (*ks__str1 > *ks__str2) {
            return 1;
        }
        if (*ks__str1 < *ks__str2) {
            return -1;
        }
        ks__str1++;
        ks__str2++;
    }
    if (*ks__str1 != '\0') {
        return 1;
    }
    if (*ks__str2 != '\0') {
        return -1;
    }
    return 0;
}

#endif
